import React, { useCallback, useState } from 'react';
import { Button, Col, Modal, Row, Space, Table, Tag, Tooltip, message } from 'antd';
import { Descriptions } from 'antd';
import 'react-quill/dist/quill.snow.css';
import JSZip from 'jszip';
import FileSaver from 'file-saver';
import axios from 'axios';
import ExportJsonExcel from "js-export-excel";
import { TableRowSelection } from 'antd/lib/table/interface';
import { useEffect } from 'react';
import { getAllRegister, getdetail, setActivityPass } from '@/services/activityInfo';
import { Link } from 'umi';
interface DataType {
  key: React.Key;
  name: string;
  age: number;
  address: string;
}
const ActivityForm: React.FC = (props) => {
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [activityDetails, setActivityDetails] = useState<any>();
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    console.log('selectedRowKeys changed: ', newSelectedRowKeys);
    setSelectedRowKeys(newSelectedRowKeys);
  };
  // 批量下载
  const patchDownload = (value: any) => {
    console.log(value)
    const zip = new JSZip();
    const imgsss: JSZip | null = zip.folder('批量下载');
    const promises: Promise<any>[] = [];
    value.forEach((item) => {
      const promise = getFile(item.fileId).then((data: any) => {
        // 下载文件, 文件名
        const file_name = decodeURIComponent(data.headers.get("content-disposition").split('filename=')[1].replace(/"/g, ''));
        // 逐个添加文件
        imgsss?.file(file_name, data.data, { binary: true });

      });
      promises.push(promise);
    });
    Promise.all(promises).then(() => {
      zip.generateAsync({ type: 'blob' }).then((content) => {
        // 生成二进制流,利用file-saver保存文件
        FileSaver.saveAs(content, '批量下载.zip');
      }).catch(() => {
        // 如果有资源文件下载失败，就直接用a链接下载
        message.error("压缩文件下载失败")
        // value.forEach((item) => {
        //     File.download({ url: "/api/freshSystem/downloadFile/" + item.fileId, fileName: item.name });
        // });
      });

    });
  }
  //单个文件下载
  const getDownLoad = (value: any) => {
    if (value) {
      window.open("/api/freshSystem/downloadFile/" + value)
    } else {
      message.warn("文件列表为空")
    }
  }
  // 请求文件资源
  const getFile = useCallback((value: string) => {
    let url = "/api/freshSystem/downloadFile/" + value
    console.log(url)
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url,
        responseType: 'blob',
      }).then((data) => {
        console.log(data)
        resolve(data);
      }).catch((error) => {
        reject(error.toString());
      });

    });
  }, []);
  const handleExportCurrentExcel = (ExcelData: any) => { //ExcelData为后端返回的data数组
    let sheetFilter = ["stuName", "stuCode", "major", "stuClass"];
    let option = {
      fileName: '',
      datas: {
      },
    };
    option.fileName = '报名详情';
    option.datas = [
      {
        sheetData: ExcelData,
        sheetName: '报名详情',
        sheetFilter: sheetFilter,
        sheetHeader: ['姓名', '学号', '专业', '班级'],
        columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
      },
    ];
    var toExcel = new ExportJsonExcel(option); //new
    toExcel.saveExcel(); //保存
  }
  const rowSelection: TableRowSelection<DataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
    selections: [
      Table.SELECTION_ALL,
      Table.SELECTION_INVERT,
      Table.SELECTION_NONE,
    ],
  };
  const [isFormModalOpen, setIsFormModalOpen] = useState(false);
  const registerColumns = [
    {
      title: '姓名',
      dataIndex: 'stuName',
      align: 'center',
      render: (text, record) => {
        return <Link to={"/StudentMessage/StudentInfoDetail?stuCode=" + record.stuCode}>{text}</Link>
      }
    },
    {
      title: '学号',
      dataIndex: 'stuCode',
      align: 'center',
    },
    {
      title: '专业',
      dataIndex: 'majorLabel',
      align: 'center',
    },
    {
      title: '班级',
      dataIndex: 'classLabel',
      align: 'center',
    },
    {
      title: '附件',
      dataIndex: 'fileId',
      align: 'center',
      render: (_: any, record: any) => (
        <Space size="middle">
          <Button type="primary" onClick={() => getDownLoad(record.fileId)}>
            附件下载
          </Button>
        </Space>
      ),
    },
    {
      title: '操作',
      align: 'center',
      render: (_: any, record: any) => (
        <div>
          <Button
            style={{ marginRight: '24px' }}
            type={record.isAudited === '0' ? 'primary' : 'default'}
            disabled={record.isAudited === '1'}
            onClick={() => handlePassClick(record.stuCode)}
          >
            {record.isAudited === '0' ? '通过' : '已通过'}
          </Button>
        </div>
      ),
    },
  ];

  // 审批通过按钮
  const handlePassClick = (stuCode: string) => {
    const data = {
      stuCodes: [stuCode],
      activityId: props.activityId,
    };
    setActivityPass(data)
      .then((response) => {
        console.log('API response:', response);
        if (response.code == 200 && response.result == 'true') {
          getallRegister()
        }
      })
      .catch((error) => {
        console.error('API error:', error);
      });
  };

  const [registerTabelData, setRegisterTabelData] = useState<any[]>([]);
  /*
数据请求
--------------------------------------------------------------------------------------------------
 */
  const getallRegister = () => {
    getAllRegister(props.activityId)
      .then((response: any) => {
        // 将result数组中的每个对象转换为所需的新数据结构
        const formattedDataArray = response.result.map((item: any) => ({
          stuName: item.studentInfo.stuName,
          stuCode: item.studentInfo.stuCode,
          majorLabel: item.studentInfo.majorLabel,
          classLabel: item.studentInfo.classLabel,
          fileId: item.fileId,
          isAudited: item.isAudited === "1" ? "1" : "0",
        }));
        // console.log(formattedDataArray);
        // 更新表格数据，使用新的数据结构
        setRegisterTabelData(formattedDataArray);
      })
      .catch((error) => {
        console.error('API错误:', error);
      });
  }
  useEffect(() => {
    getdetail(props.activityId).then((response: any) => {
      const activity = response.result;

      // 格式化时间函数
      const formatDate = (datetimeString) => {
        const datetime = new Date(datetimeString);
        const year = datetime.getFullYear();
        const month = (datetime.getMonth() + 1).toString().padStart(2, '0');
        const day = datetime.getDate().toString().padStart(2, '0');
        const hours = datetime.getHours().toString().padStart(2, '0');
        const minutes = datetime.getMinutes().toString().padStart(2, '0');
        const seconds = datetime.getSeconds().toString().padStart(2, '0');
        return `${year}年${month}月${day}日 ${hours}:${minutes}:${seconds}`;
      };

      // 格式化 endTime
      activity.endTime = formatDate(activity.endTime);

      // 格式化 registrationDeadline
      activity.registrationDeadline = formatDate(activity.registrationDeadline);

      // 格式化 startTime
      activity.startTime = formatDate(activity.startTime);
      if (activity.activityLevel == 0 || activity.activityLevel == "0") activity.activityLevel = "国家级"
      else if (activity.activityLevel == 1 || activity.activityLevel == "1") activity.activityLevel = "省级"
      else if (activity.activityLevel == 2 || activity.activityLevel == "2") activity.activityLevel = "校级"
      else if (activity.activityLevel == 3 || activity.activityLevel == "3") activity.activityLevel = "院级"
      if (activity.activityCategory == 0 || activity.activityCategory == "0") activity.activityCategory = "活动竞赛"
      else if (activity.activityCategory == 1 || activity.activityCategory == "1") activity.activityCategory = "评奖评优"
      else if (activity.activityCategory == 2 || activity.activityCategory == "2") activity.activityCategory = "学生组织"
      setActivityDetails(response.result)
    })
    getallRegister()
  }, []); // 空依赖数组确保该 effect 仅在组件挂载时执行一次
  /*
  --------------------------------------------------------------------------------------------------
  数据请求
   */
  return (
    <div>
      <Modal title="报名详情" width="60%" open={isFormModalOpen} footer={null} onCancel={() => setIsFormModalOpen(false)}>
        <Space direction="vertical" size="middle" style={{ display: 'flex' }}>
          <Space>
            <Button type="primary" style={{ marginRight: '24px' }} >
              批量通过
            </Button>
            <a style={{ marginRight: '32px' }} onClick={() => patchDownload(registerTabelData)}>
              批量下载
            </a>
            <a onClick={() => handleExportCurrentExcel(registerTabelData)}>
              导出表格
            </a>
          </Space>
          <Table rowSelection={rowSelection} columns={registerColumns} dataSource={registerTabelData} size="small" />
        </Space>
      </Modal>
      <Row>
        <Col xl={24} lg={24} md={24} sm={24} xs={24}>
          <Descriptions
            bordered={true}
            column={2}
          >
            <Descriptions.Item label="活动名称">
              {activityDetails?.activityLabel || ''}
            </Descriptions.Item>
            <Descriptions.Item label="举办方">
              {activityDetails?.organizationalUnit || ''}
            </Descriptions.Item>
            <Descriptions.Item label="活动级别">
              {activityDetails?.activityLevel || ''}
            </Descriptions.Item>
            <Descriptions.Item label="活动类型">
              {activityDetails?.activityCategory || ''}
            </Descriptions.Item>
            <Descriptions.Item label="负责人">
              {activityDetails?.teaName || ''}
            </Descriptions.Item>
            <Descriptions.Item label="嘉宾">
              {activityDetails?.guest || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b>举办地点</b>}>
              {activityDetails?.activityAddress || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b>举办日期</b>}>
              {activityDetails?.startTime || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b style={{ color: '#c00000' }}>报名截止日期</b>}>
              {activityDetails?.registrationDeadline || ''}
            </Descriptions.Item>
            <Descriptions.Item label={<b style={{ color: '#c00000' }}>活动截止日期</b>}>
              {activityDetails?.endTime || ''}
            </Descriptions.Item>
            <Descriptions.Item
              span={2}
              contentStyle={{
                maxWidth: '80%',
                maxHeight: '80%'
              }}
              label="活动内容"
            >
              {activityDetails?.activityContent || ''}
            </Descriptions.Item>
            <Descriptions.Item label="附件" >
              <a onClick={() => {
                if (activityDetails?.fileId) {
                  const fileList = activityDetails?.fileId.split(",")
                  console.log(fileList)
                  patchDownload(fileList)
                  message.success("下载成功")
                } else {
                  message.warn("文件列表为空")
                }
              }}>下载附件</a>
            </Descriptions.Item>

            <Descriptions.Item label="报名信息">
              <a onClick={() => setIsFormModalOpen(true)}>查看</a>
            </Descriptions.Item>
          </Descriptions>


        </Col>
      </Row>
    </div>
  );
};

export default ActivityForm;
function handleDelete(record: any) {
  throw new Error('Function not implemented.');
}

